package com.ccp.dev.workflow.service;

import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.model.FormTable;
import com.ccp.dev.form.service.FormDefService;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.form.service.FormTableService;
import com.ccp.dev.workflow.dao.*;
import com.ccp.dev.workflow.model.BpmGangedSet;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassDescribe:联动设置表 Service层
 */
@Service
public class BpmGangedSetService{

    @Resource
    private BpmGangedSetDao bpmGangedSetDao;
    @Resource
    private FormDefService formDefService;
    @Resource
    private FormFieldService formFieldService;
    @Resource
    private FormTableService formTableService;

    /**
     * 过滤字段类型，只选取下拉框、单选按钮、复选框
     * @param tableFields
     */
    private List<FormField> filterFields(List<FormField> tableFields){
        List<FormField> temp = new ArrayList<FormField>();
        for(FormField formFields:tableFields){
            Short cType = formFields.getControlType();
            if(cType==11||cType==13||cType==14){
                temp.add(formFields);
            }
        }
        return temp;
    }

    public String getFieldsByFormkey(String formKey, boolean isNeedFilter) {
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        FormDef formDef = formDefService.getDefaultVersionByFormKey(formKey);
        String tableId = formDef.getTableId();

        FormTable mainTable = formTableService.getOneById(tableId);
        List<FormField> mainTableFields = formFieldService.getByTableId(tableId);
        //是否过滤字段类型（选择框字段需要过滤，变更字段无需过滤）
        if(isNeedFilter) {
            mainTableFields = this.filterFields(mainTableFields);
        }
        sb.append(getJson(mainTable, mainTableFields,true,isNeedFilter));
        List<FormTable> subTables = formTableService.getSubTableByMainTableId(tableId);
        for(FormTable subTable:subTables){
            String subTableId = subTable.getTableId();
            List<FormField> subFields = formFieldService.getByTableId(subTableId);
            //是否过滤字段类型（选择框字段需要过滤，变更字段无需过滤）
            if(isNeedFilter) {
                subFields = this.filterFields(subFields);
            }

            sb.append(getJson(subTable, subFields,false,isNeedFilter));
        }
        sb.append("]");
        return sb.toString();
    }


    /**
     * 获取json
     * @param table 表
     * @param fields 字段
     * @param isNeedFilter  是否过滤
     * @return
     */
    public String  getJson(FormTable table,List<FormField> fields,Boolean isMain, Boolean isNeedFilter){
        if(BeanUtils.isEmpty(fields)) { return ""; }
        StringBuffer sb = new StringBuffer();
        JSONArray jsonArray = new  JSONArray();
        JSONArray jArray = JSONArray.fromObject(fields);
        //不是主表并且不是进行过滤
        if(!isMain && !isNeedFilter){
            FormField field = new FormField();
            field.setFieldId(table.getTableId());
            field.setType((short) 1);
            field.setFieldName(table.getTableName());
            field.setFieldDesc(table.getTableDesc());
            jsonArray.add(field);
        }
        jsonArray.addAll(jArray);

        if(!isMain) {
            sb.append(",");
        }
        sb.append("{name:\"")
                //表没有填写描述时，取表名
                .append(StringUtil.isEmpty(table.getTableDesc())?table.getTableName():table.getTableDesc())
                .append("\",key:\"")
                .append(table.getTableName())
                .append("\",type:")
                .append(isMain?"1":"0")
                .append(",fields:")
                .append(jsonArray.toString())
                .append("}");
        return sb.toString();
    }

    public List<BpmGangedSet> queryAll(String modelId) {
        return bpmGangedSetDao.queryAll(modelId);
    }

    public void delByIdArray(String[] ids) {
        bpmGangedSetDao.delByIdArray(ids);
    }

    /**
     * 批量保存联动设置，并删除不在保存列表中的记录
     * @param modelId
     * @param json
     */
    public void batchSave(String modelId,String json){
        List<String> gangedSetId = new ArrayList<String>();
        if(StringUtil.isEmpty(json)){
            delByDefIdExceptSetIds(modelId, gangedSetId);
            return;
        }
        JSONArray jArray = (JSONArray)JSONArray.fromObject(json);
        for(Object object:jArray){
            JSONObject jObject = (JSONObject)object;
            String id = jObject.getString("id");
            BpmGangedSet gangedSet;
            if(StringUtil.isNotEmpty(id)){
                gangedSet = bpmGangedSetDao.getById(id);
                gangedSetId.add(id);
            }
            else{
                String newId = UUIDUtils.getUUIDFor32();
                gangedSet = new BpmGangedSet();
                gangedSet.setId(newId);
                gangedSetId.add(newId);
            }
            gangedSet.setModelId(jObject.getString("modelId"));
            gangedSet.setNodeId(jObject.getString("nodeId"));
            gangedSet.setNodeName(jObject.getString("nodeName"));
            gangedSet.setChooseField(jObject.getString("chooseField"));
            gangedSet.setChangeField(jObject.getString("changeField"));
            if(StringUtil.isNotEmpty(id)) {
                bpmGangedSetDao.update(gangedSet);
            }else {
                bpmGangedSetDao.add(gangedSet);
            }
        }
        delByDefIdExceptSetIds(modelId, gangedSetId);
    }

    /**
     * 通过 modelId 删除除了setIds以外的记录
     * @param modelId
     * @param setIds
     */
    private void delByDefIdExceptSetIds(String modelId,List<String> setIds){
        String ids = "";
        for(String setId:setIds){
            if(StringUtil.isEmpty(ids)) {
                ids += "'"+setId+"'";
            }else{
                ids += ",";
                ids += "'"+setId+"'";
            }
        }
        bpmGangedSetDao.delByDefIdExceptSetId(modelId, ids);
    }

    /**
     * 通过流程定义ID获取联动设置
     * @param modelId
     * @return
     */
    public List<BpmGangedSet> queryByModelId(String modelId) {
        return bpmGangedSetDao.queryByModelId(modelId);
    }
}